package com.xunji.standard.zip;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;

/**
 * @Author: xuqiang_imyours
 * @Date: 2025/6/26 11:47
 * @Description:
 **/
public class ExcelCompressionUtils {

    public static Logger log = LoggerFactory.getLogger(ExcelCompressionUtils.class);


    public static void main(String[] args) {
        System.out.println(isExcelEncrypted("D:\\xunji\\st-standard\\xlsx-jiami.xlsx", "1234"));

        File file = new File("D:\\xunji\\st-standard\\xlsx-jiami.xlsx");
        String name = file.getName();
        String newName = name.substring(0, name.lastIndexOf(".")) + "_[" + "password" + "]" + name.substring(name.lastIndexOf("."));
        System.out.println(file.getParent() + File.separator + newName);
    }

    /**
     * 验证是否存在密码
     *
     * @param filePath 文件路径
     * @return true 存在密码  false不存在密码
     */
    public static boolean isExcelEncrypted(String filePath) {
        boolean result = false;
        File file = new File(filePath);
        try {
            Workbook ignored = WorkbookFactory.create(file, null, true);
            // 能正常打开说明未加密
        } catch (Exception e) {
            log.error("尝试读取excel文件异常，文件已加密，错误信息：{}", e.getMessage());
            result = true;
        }
        return result;
    }


    /**
     * 密码验证excel读取结果
     *
     * @param filePath 文件路径
     * @param password 密码
     * @return true密码正确  false密码错误
     */
    public static boolean isExcelEncrypted(String filePath, String password) {
        boolean result = true;
        File file = new File(filePath);
        try {
            Workbook ignored = WorkbookFactory.create(file, password, true);
            // 能正常打开说明未加密
        } catch (Exception e) {
            log.error("密码读取excel文件异常，密码错误，错误信息：{}", e.getMessage());
            result = false;
        }
        return result;
    }
}
